package com.example.s01_helloworld.controller;

import com.example.s01_helloworld.model.User;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.List;

@RestController
public class UserController {


    // ReqeustMapping  映射路径
    // name    请求路径
    // method  请求方法
        // RequestMethod.POST
        // RequestMethod.GET
//    @RequestMapping("/getUser")
    @RequestMapping(value="/getUser", method= RequestMethod.GET)
    public User getUser() {
        User user=new User();
        user.setName("小明");
        user.setAge(12);
        user.setPass("123456");
        return user;
    }

    // 如果限定了 method= RequestMethod.POST
    // 如果使用GET方式请求则会显示405
    // There was an unexpected error (type=Method Not Allowed, status=405).

    // 自动绑定-简单参数
    @RequestMapping(value = "/getUser2")
    public User getUser2(String username,int age,String password)
    {
        User user=new User();
        user.setName(username);
        user.setAge(age);
        user.setPass(password);
        return user;
    }

//  测试:  http://localhost:8080/getUser3?name=zhangsan&age=18&pass=123456
    // 自动绑定-绑定到对象
    @RequestMapping(value = "/getUser3")
    public User getUser3(User user)
    {
        return user;
    }

    // @RequestParam
    //      value           指定用户提交的参数名
    //      requiired       要求是否必须体用
    //      defaultValue    默认值（如果用户没有提交)
    @RequestMapping(value = "/getUser4")
    public User getUser4(String username,
                         @RequestParam(value = "age",required = true,defaultValue = "18") int age,
                         @RequestParam(value = "pass") String password)
    {
        User user=new User();
        user.setName(username);
        user.setAge(age);
        user.setPass(password);
        return user;
    }

    // @Valid 要检测的参数对象
    // BindingResult result     保存检测结果
    @RequestMapping("/saveUser")
    public String saveUser(@Valid User user, BindingResult result)
    {
        // hasErrors() 返回是否验证成功
        if(result.hasErrors())
        {
            // getAllErrors() 所有校验失败的信息
            List<ObjectError> list = result.getAllErrors();
            StringBuilder sb = new StringBuilder();
            for (ObjectError error : list) {
                System.out.println(error.getCode()+ "-" + error.getDefaultMessage());
                sb.append(error.getDefaultMessage()+",");
            }
            return "保存失败,错误信息:"+sb.toString();
        }
        return "保存成功";
    }
}
